<template>
  <div class="app-container">
    <div class="searchBox">
      <el-form :inline="true" :model="search" ref="searchForm">
        <el-form-item label="标题：" prop="title">
          <el-input v-model="search.title" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="分类：" prop="categoryId">
          <el-select v-model="search.categoryId">
            <el-option
              v-for="item in controlData.noticeCategorys"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-select v-model="search.status">
            <el-option
              v-for="item in controlData.statusList"
              :key="item.key"
              :label="item.key"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="margin-top: -2px">
          <el-button type="primary" @click="searchQuery">查询</el-button>
          <el-button type="info" @click="search = {};searchQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <qm-table
      ref="qmTable"
      :data="query"
      keyProp="noticeId"
      menuType="text"
      :formOptions="{ labelWidth: '120px' }"
      :menuOptions="{ width: 200 }"
      :modalOptions="{ height: 630 }"
      :rules="rules"
    >
      <qm-table-column field="categoryName" width="120">分类名称</qm-table-column>
      <qm-table-column field="title">标题</qm-table-column>
      <qm-table-column field="creatorName" width="90">创建人</qm-table-column>
      <qm-table-column field="publishTime" width="160">发布时间</qm-table-column>
      <qm-table-column field="createTime" sortable width="160">创建时间</qm-table-column>
      <qm-table-column
        field="status"
        width="90"
        fieldtype="enum"
        :enumOptions="[
          { key: '已发布', value: true },
          { key: '草稿', value: false },
        ]"
        sortable
      >状态
      </qm-table-column>
      <template v-slot:moreBtn="{ row }">
        <el-button
          v-if="row.status"
          style="padding-left: 7px"
          size="mini"
          type="text"
          @click.native="updateStatus(row, false)"
        >取消发布
        </el-button>
        <el-button
          v-else
          style="padding-left: 7px"
          size="mini"
          type="text"
          @click.native="updateStatus(row, true)"
        >发布
        </el-button>
      </template>
      <template v-slot:form="{ model, pageAction, disabled }">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题：" prop="model.title">
              <el-input v-model="model.title"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布时间：" prop="model.publishTime">
              <el-date-picker
                v-model="model.publishTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类：" prop="model.categoryId">
              <el-select v-model="model.categoryId">
                <el-option
                  v-for="item in controlData.noticeCategorys"
                  :key="item.categoryId"
                  :label="item.categoryName"
                  :value="item.categoryId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否置顶：" prop="model.isTop">
              <el-radio v-model="model.isTop" :label="true">是</el-radio>
              <el-radio v-model="model.isTop" :label="false">否</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="显示有效期：" prop="model.availableStartTime">
              <el-date-picker
                v-model="model.availableStartTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                required
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="至：" prop="model.availableEndTime">
              <el-date-picker
                v-model="model.availableEndTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                required
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="摘要：" prop="model.summary">
              <el-input
                type="textarea"
                :autosize="{ minRows: 5, maxRows: 20 }"
                v-model="model.summary"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="公告内容：" prop="model.content">
              <el-upload
                class="avatar-uploader"
                style="display: none"
                :action="serverUrl"
                :show-file-list="false"
                :on-success="uploadImgSuccess"
                :on-error="uploadImgError"
                :before-upload="beforeImgUpload"
              >
              </el-upload>
              <editor ref="editor" v-model="model.content" :min-height="192" :disabled="disabled" :options="editorOption"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <qm-file-upload
              :dataKey="model.noticeId"
              :editable="pageAction != 'view'"
              title="附件上传"
              fileSize="20"
              fileType=".jpg,.png,.doc,.docx,.xls,.xlsx,.pdf,.txt,.zip,.rar"
              @uploaded="uploadSuccess"
              viewType="office"
            ></qm-file-upload>
          </el-col>
        </el-row>
      </template>
    </qm-table>
  </div>
</template>

<script>
import Controller from '@/libs/framework/controller'
import request from '@/utils/request'
import Editor from '@/components/Editor'
import QmFileUpload from '@/libs/components/qm-file-upload'
// 工具栏配置
const toobarOptioins = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
  ['blockquote', 'code-block'], // 引用  代码块
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
  [{ indent: '-1' }, { indent: '+1' }], // 缩进
  [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
  [{ align: [] }], // 对齐方式
  ['clean'], // 清除文本格式
  ['link', 'image', 'video'] // 链接、图片、视频
]

export default class Instance extends Controller {
  onBeforeInit() {
    this.urls = {
      query: [{ url: '/admin/sysNotice/query', method: 'post' }],
      save: '/admin/sysNotice/save',
      delete: '/admin/sysNotice/delete',
      entity: '/admin/sysNotice/getEntity'
    }
    this.urls.model = '/admin/sysNotice/getListModel'
  }


  mixin() {
    return {
      components: {
        Editor,
        QmFileUpload
      },
      data() {
        return {
          quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画
          serverUrl: process.env.VUE_APP_BASE_API+'/attachment/upload',  // 上传的图片服务器地址
          editorOption: {
            modules: {
              toolbar: {
                container: toobarOptioins,  // 工具栏
                handlers: {
                  'image': function(value) {
                    if (value) {
                      document.querySelector('.avatar-uploader input').click()
                    } else {
                      this.quill.format('image', false)
                    }
                  }
                }
              }
            }
          },
          rules: {
            model: {
              title: [
                {
                  required: true,
                  message: '这是必填字段',
                  trigger: 'blur'
                }
              ],
              categoryId: [
                {
                  required: true,
                  message: '这是必填字段',
                  trigger: 'blur'
                }
              ],
              content: [
                {
                  required: true,
                  message: '这是必填字段',
                  trigger: 'blur'
                }
              ],
              publishTime: [
                {
                  required: true,
                  message: '这是必填字段',
                  trigger: 'blur'
                }
              ]
            }
          }
        }
      },
      methods: {
        // 上传图片前
        beforeImgUpload(res, file) {
          // 显示loading动画
          this.quillUpdateImg = true
        },
        // 上传图片成功
        uploadImgSuccess(res, file) {
          // res为图片服务器返回的数据
          // 获取富文本组件实例
          let quill = this.$refs.editor.quill
          // 如果上传成功
          if (res!=null && res.attachmentId!=null) {
            // 获取光标所在位置
            let length = quill.selection.savedRange.index
            // 插入图片  res.info为服务器返回的图片地址
            let attachmentId = res.attachmentId;
            let attachUrl = process.env.VUE_APP_BASE_API+"/attachment/download?attachmentId=" + attachmentId;
            quill.insertEmbed(length, 'image', attachUrl)
            // 调整光标到最后
            quill.setSelection(length + 1)
          } else {
            this.$message.error('插入失败')
          }
          // loading动画消失
          this.quillUpdateImg = false
        },
        // 上传图片失败
        uploadImgError(res, file) {
          // loading动画消失
          this.quillUpdateImg = false
          this.$message.error('图片插入失败')
        },

        uploadSuccess(attachment) {
          let vm = this.$refs['qmTable'].viewModel
          vm.models.attachmentIds =
            (vm.models.attachmentIds || '') + `,${attachment.attachmentId}`
        },
        updateStatus(row, noticeStatus) {
          let msg = noticeStatus ? '发布' : '取消发布'
          this.$confirm('确定要' + msg + '吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              request({
                url: '/admin/sysNotice/updateStatus',
                method: 'post',
                data: {
                  noticeId: row.noticeId,
                  noticeStatus: noticeStatus
                }
              })
                .then((r) => {
                  if (r && !r.initMessage) {
                    this.$message({
                      message: msg + '成功',
                      type: 'success'
                    })
                  } else {
                    reject(r.initMessage || '数据请求失败')
                  }
                  this.$refs['qmTable'].refresh()
                })
                .catch((e) => {
                  reject(e)
                })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作'
              })
            })
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
</style>

